package com.jp.fm.datacollector;

import static org.junit.Assert.fail;

import java.text.NumberFormat;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.jp.fm.HomeFinanceRunner;
import com.jp.fm.dao.AccountDao;
import com.jp.fm.data.Account;
import com.jp.fm.data.UserAccount;

public class SelAESAEP extends SelParent {
	private WebDriver driver;
	private StringBuffer verificationErrors = new StringBuffer();

	@Before
	public final void setUp() throws Exception {
		this.driver = new FirefoxDriver();
		this.driver.manage().timeouts()
				.implicitlyWait(AllTests.WAIT_TIME_SECONDS, TimeUnit.SECONDS);
	}

	@Test
	public final void testSelAESAEP() throws Exception {

		// Lookup username, password and url
		UserAccount uAcct = UserAccount.findByRunClass(this.getClass()
				.getName());
		String url = uAcct.getAttribute(UserAccount.URL);
		String username = uAcct.getUsername();
		String password = uAcct.getPassword();
		String name = uAcct.getName();

		this.driver.get(url);
		this.driver.findElement(By.id("username")).clear();
		this.driver.findElement(By.id("username")).sendKeys(username);
		this.driver.findElement(By.name("studentSignIn")).click();

		this.driver.findElement(By.id("password")).clear();
		this.driver.findElement(By.id("password")).sendKeys(password);
		this.driver.findElement(By.id("btnSubmit")).click();

		String balance = this.driver
				.findElement(
						By.xpath("//table[@class='loanSummaryTable']//tfoot//tr//td//span"))
				.getText();
		balance = StringUtils.remove(balance, ' ');
		Number balanceNum = NumberFormat.getCurrencyInstance().parse(balance);
		Float balanceFloat = balanceNum.floatValue();

		this.driver.findElement(By.id("logout")).click();

		// Update account balance
		Account account = getAccountDao().findByName(name);
		balanceFloat *= -1;
		account.setBalance(balanceFloat);
		getAccountDao().writeObject(account);
		System.out.println("Account updated");

		HomeFinanceRunner.getCache(AccountDao.CACHE_NAME).removeAll();
		System.out.println("Account< " + account.getName() + "> cache cleared");
	}

	@After
	public final void tearDown() throws Exception {
		this.driver.quit();
		String verificationErrorString = this.verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}
}
